package com.common.util;

//~--- non-JDK imports --------------------------------------------------------

import net.sf.json.JSONObject;
import org.apache.commons.lang.RandomStringUtils;
import java.util.*;

//~--- JDK imports ------------------------------------------------------------

//~--- classes ----------------------------------------------------------------

/**
 * Class TLinx2Util
 * Description tlinx api 工具类
 * Create 2017-03-07 14:01:23
 * @author Benny.YEE
 */
public class TLinx2Util {

    /**
     * 签名
     * @param postMap
     * @param privatekey 说明：
     * @return
     */
    public static String sign(Map<String, String> postMap, String privatekey) {
        String sortStr = null;
        String sign    = null;

        try {

            /**
             * 1 A~z排序
             */
            sortStr = sort(postMap);
            System.out.println("=======排序后的明文：" + sortStr);

            /**
             * 2 sha1加密(小写)
             */
            String sha1 = TLinxSHA1.SHA1(sortStr);

            System.out.println("=======sha1：" + sha1);

            /**
             * 3 RSA加密(小写),二进制转十六进制
             */
            sign = TLinxRSACoder.sign(sha1.getBytes("utf-8"), privatekey);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sign;
    }

    /**
     * 验签
     * @param respObject
     * @param publickey 说明：
     * @return
     */
    public static Boolean verifySign(JSONObject respObject, String publickey) {
        boolean verify = false;
        try {
            String respSign = respObject.getString("sign");

            respObject.remove("sign");                          // 删除sign节点

            String rspparm = sortjson(respObject);    // ȥsign json
            String sha1    = TLinxSHA1.SHA1(rspparm);           // sha1����

            verify = TLinxRSACoder.verify(sha1.getBytes(), publickey, respSign);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return verify;
    }

    /**
     * AES加密，再二进制转十六进制(bin2hex)
     * @param datamap 说明：
     *
     * @return 返回值说明：
     * @throws Exception
     */
    public static String handleEncrypt(TreeMap<String, String> datamap) throws Exception {
        JSONObject dataobj = JSONObject.fromObject(datamap);
        return TLinxAESCoder.encrypt(dataobj.toString(), StaticConfig.open_key);    // AES加密，并bin2hex
    }

    /**
     * 签名
     * @param getmap
     * @param datamap 说明：
     *
     * @return 返回值说明：
     */
    public static String handleSign(TreeMap<String, String> getmap, TreeMap<String, String> datamap) {
        Map<String, String> veriDataMap = new HashMap<String, String>();

        veriDataMap.putAll(getmap);
        veriDataMap.putAll(datamap);

        // 签名
        return sign(veriDataMap, StaticConfig.privatekey);
    }




    /**
     * Method main
     * Description 说明：
     *
     * @param args 说明：
     */
    public static void main(String[] args) {
        // 初始化参数
        String page      = "1";
        String pagesize  = "10";
        String mctNo     = "20747484";
        String traId     = "TEST000000000000001";
        String timestamp = new Date().getTime() / 1000 + "";    // 时间


 
   try {
	   TreeMap<String, String> datamap = new TreeMap<String, String>();    // data参数的map
       datamap.put("page", page);
       String data = handleEncrypt(datamap);
      
       System.out.println("=====data=====" + data);  
       String respData = TLinxAESCoder.decrypt(data, StaticConfig.open_key);
       System.out.println("=====data=====" + respData); 
} catch (Exception e) {
	// TODO: handle exception
}

   
          
    }

    // 排序
    public static String sort(Map paramMap) throws Exception {
        String sort = "";
        TLinxMapUtil signMap = new TLinxMapUtil();
        if (paramMap != null) {
            String key;
            for (Iterator it = paramMap.keySet().iterator(); it.hasNext();) {
                key = (String) it.next();
                String value = ((paramMap.get(key) != null) && (!(""
                        .equals(paramMap.get(key).toString())))) ? paramMap
                        .get(key).toString() : "";
                signMap.put(key, value);
            }
            signMap.sort();
            for (Iterator it = signMap.keySet().iterator(); it.hasNext();) {
                key = (String) it.next();
                sort = sort + key + "=" + signMap.get(key).toString() + "&";
            }
            if ((sort != null) && (!("".equals(sort)))) {
                sort = sort.substring(0, sort.length() - 1);
            }
        }
        return sort;
    }


    // 排序
    public static String sortjson(JSONObject jsonMap) throws Exception {
        Map<String ,String > paramMap=new HashMap<String, String>();
        // 将json字符串转换成jsonObject
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        Iterator ite = jsonObject.keys();
        // 遍历jsonObject数据,添加到Map对象
        while (ite.hasNext()) {
            String key = ite.next().toString();
            String value = jsonObject.get(key).toString();
            paramMap.put(key, value);
        }
        String sort = "";
        TLinxMapUtil signMap = new TLinxMapUtil();
        if (paramMap != null) {
            String key1;
            for (Iterator it = paramMap.keySet().iterator(); it.hasNext();) {
                key1 = (String) it.next();
                String value = ((paramMap.get(key1) != null) && (!(""
                        .equals(paramMap.get(key1).toString())))) ? paramMap
                        .get(key1).toString() : "";
                signMap.put(key1, value);
            }
            signMap.sort();
            for (Iterator it = signMap.keySet().iterator(); it.hasNext();) {
                key1 = (String) it.next();
                sort = sort + key1 + "=" + signMap.get(key1).toString() + "&";
            }
            if ((sort != null) && (!("".equals(sort)))) {
                sort = sort.substring(0, sort.length() - 1);
            }
        }
        return sort;
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
